//
//  YD_ManagerTool.m
//  ziru
//
//  Created by isu on 16/7/30.
//  Copyright © 2016年 isu. All rights reserved.
//

#import "HcardManagerTool.h"
#import <AVFoundation/AVFoundation.h>

//#import "LGAudioKit.h"//->.caf转->arm文件
@implementation HcardManagerTool
+ (void)requestWithURLString:(NSString *)URLString
                  parameters:(id)parameters
                        type:(HttpRequestType)type
                     success:(void (^)(id))success
                     failure:(void (^)(NSError *))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    switch (type) {
        case HttpRequestTypeGet:
        {
            [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (success) {
                    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    success(JSON);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;
        case HttpRequestTypePost:
        {
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (success) {
                    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    success(JSON);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;
        case HttpRequestTypePostAndJSON:
        {
            //申明返回的结果是json类型
            // manager.responseSerializer = [AFJSONResponseSerializer serializer];
            //申明请求的数据是json类型
            manager.requestSerializer=[AFJSONRequestSerializer serializer];
            //如果报接受类型不一致请替换一致text/html或别的
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (success) {
                    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    success(JSON);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failure) {
                    failure(error);
                }
            }];
        }
            break;
    }
}
+ (void)uploadImageWithImage:(UIImage *)image
                        Url :(NSString*)url
                  Dictionary:(NSDictionary *)dictionary
                     success:(void (^)(id))success
                     failure:(void (^)(NSError *))failure {
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    float length = [imageData length]/1024;
    float scale = 1.0f;
    //    if (length > 100) {
    //        scale = 100.0 / length ;
    //    }else{
    //        scale = 1.0f;
    //    }
    //    if (length>1024) {//1M以及以上
    //        scale = 0.1;
    //    } else if (length>512) {//0.5M-1M
    //        scale = 0.4;
    //    }else if (length>200) {//0.25M-0.5M
    //        scale = 0.8;
    //    }
    CGFloat dataSize = length;
    CGFloat width  = image.size.width;
    CGFloat height = image.size.height;
    CGSize size;
    if (dataSize<=100) {
        size = CGSizeMake(width/1.f, height/1.f);
    } else if (dataSize<=200) {
        size = CGSizeMake(width/1.2f, height/1.2f);
    } else if (dataSize<=500) {
        size = CGSizeMake(width/1.5f, height/1.5f);
    } else if (dataSize<=1000) {
        size = CGSizeMake(width/1.8f, height/1.8f);
    } else if (dataSize<=2000) {
        size = CGSizeMake(width/2.0f, height/2.0f);
    } else {
        size = CGSizeMake(width/2.4f, height/2.4f);
    }
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0,0, size.width, size.height)];
    UIImage *newImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *fData = UIImageJPEGRepresentation(newImage, scale);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [manager POST:url parameters:dictionary constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *respDic = responseObject;
        success(respDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

+ (void)upLoadVideoWithOption:(NSDictionary *)para
                withInferface:(NSString *)requestURL
                    videoPath:(NSString*)videoURL
                uploadSuccess:(void (^)(id sucess))sucess
                uploadFailure:(void (^)(NSError * error))failure
                     progress:(void (^)(NSProgress * progress))progress{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    manager.requestSerializer.timeoutInterval = 25.f;
    [manager POST:requestURL parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *videoData = [NSData dataWithContentsOfFile:videoURL];
        [formData appendPartWithFileData:videoData name:@"file" fileName:@"videoIdentify.mp4" mimeType:@"video/mpeg4"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if(uploadProgress){
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *respDic = responseObject;
        sucess(respDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);    }];
}

+(void)downLoadWithUrl:(NSString *)requestUrl
               success:(void (^)(id ))success
               failure:(void (^)(NSError * ))failure
              progress:(void (^)(NSProgress * ))progress{
    //远程地址
    NSURL *URL = [NSURL URLWithString:requestUrl];
    //默认配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //AFN3.0+基于封住URLSession的句柄
    AFHTTPSessionManager *manager =[[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    
    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    //下载Task操作
    NSURLSessionDownloadTask *downLoadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        // @property int64_t totalUnitCount;     需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小
        
        // 给Progress添加监听 KVO
        //NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        // 回到主队列刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            // 设置进度条的百分比
        });
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //设置下载完成操作
        // filePath就是你下载文件的位置
        // NSLog(@"filePath = %@",[filePath path]);
        NSData *data = [NSData dataWithContentsOfURL:filePath];
        success(data);
        if(error){
            failure(error);
        }
    }];
    [downLoadTask resume];
}

//上传语音
+(void)upLoadAudioWithUrl:(NSString *)requestUrl
              WithOptions:(NSDictionary *)para
            WithSourceUrl:(NSString *)SourceUrl
                  success:(void (^)(id ))success
                  failure:(void (^)(NSError * ))failure
                 progress:(void (^)(NSProgress * ))progress{
    // NSURL *mp3Url =  [NSURL URLWithString:SourceUrl];//本例子是将本地的 .caf 文件上传到服务器上面去
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"image/jpeg", nil];
    [manager POST:requestUrl parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //  application/octer-stream   audio/mpeg video/mp4   application/octet-stream
        
        /* url      :  本地文件路径
         * name     :  与服务端约定的参数
         * fileName :  自己随便命名的
         * mimeType :  文件格式类型 [mp3 : application/octer-stream application/octet-stream] [mp4 : video/mp4]
         */
        //        [formData appendPartWithFileURL:mp3Url name:@"file" fileName:@"myPublishAudio.mp3" mimeType:@"application/octet-stream" error:nil];
//        NSData *audioData = [[LGSoundRecorder shareInstance] convertCAFtoAMR:SourceUrl];
        // NSData *audioData = [NSData dataWithContentsOfFile:SourceUrl];
//        [formData appendPartWithFileData:audioData name:@"file" fileName:@"myPublishAudio.amr" mimeType:@"application/octet-stream"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // float progress1 = 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        //NSLog(@"上传进度-----   %f",progress);
        progress(uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // NSLog(@"上传成功 %@",responseObject);
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // NSLog(@"上传失败 %@",error);
        failure(error);
    }];
    
}

@end
